import 'dart:developer';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:ball_lion/entity/ai/ai_pay_entity.dart';
import 'package:ball_lion/entity/ai/model_entity.dart';
import 'package:ball_lion/entity/pay/recharge_entity.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/module/pick/ai/ai_type.dart';
import 'package:ball_lion/entity/pay/usable_coupon.dart';
import 'package:ball_lion/server/api/coupon_api.dart';
import 'package:ball_lion/server/api/other_api.dart';
import 'package:ball_lion/server/api/pay_api.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/pay/pay_bottom_sheet.dart';

class AiPayLogic extends GetxController {
  int _priceIndex = 0;
  String? tip;
  AiType? type = Get.arguments is AiType
      ? Get.arguments
      : AiType.getTypeByTag(Get.arguments ?? "");
  int? roomId = Get.parameters['roomId'].toInt();
  AiPayEntity? data;
  ModelEntity? info;
  List<AiPrice>? price;
  List<AiBenefit>? benefits;
  List<UsableCouponEntity>? coupons;
  List<double?> realPrice = [];
  int get priceIndex => _priceIndex;

  set priceIndex(int value) {
    _priceIndex = value;
    update();
  }

  @override
  void onReady() {
    requestData();
    super.onReady();
  }

  Future toPay(AiPrice price) async {
    Utils.onEvent('mx_ljzf');
    var x = double.parse(price.price!.split(RegExp(r"[\u4e00-\u9fa5]")).join());
    double money = x;
    final PayResult? result = await Get.bottomSheet(
        isScrollControlled: true,
        PayBottomSheet(
            payInfo: PayInfo(
                price: money.toString(),
                payScene: PayScene.ai,
                buyId: price.id.toString(),
                coupons: coupons)));
    if (result != null && result.toPay == PayStatus.goldPay) {
      var s = await PayApi.aiOrder(price.id,
          couponGold: result.coupon?.gold,
          couponId: result.coupon?.id,
          roomId: roomId);
      if (s == true) {
        Utils.onEvent('aixq_zfyd_qrzf');
        if (Get.previousRoute.contains("/pick/ai/")) {
          Get.back();
        } else {
          Get.offAndToNamed(type?.route ?? "");
        }
      } else {
        Utils.onEvent('aixq_zfyd_qxzf');
      }
    } else if (result?.toPay == PayStatus.directPay) {
      Utils.onEvent('aixq_zfyd_qrzf');
      if (Get.previousRoute.contains("/pick/ai/")) {
        Get.back();
      } else {
        Get.offAndToNamed(type?.route ?? "");
      }
    } else {
      Utils.onEvent('aixq_zfyd_qxzf');
      Toast.text("购买失败");
    }
    User.fetchUserInfo(fetchFocus: false);
  }

  Future requestData() async {
    data = await PayApi.getAiPay(type?.id ?? 0, roomId: roomId);
    info = data?.info;
    price = data?.price;
    benefits = data?.benefit;
    realPrice = price?.map((e) => 0.0).toList() ?? [];
    var tips = await OtherApi.getAppList("app_res_tips");
    try {
      tip =
          tips?.firstWhere((element) => element.button == "ai_pay_tip").content;
      update();
    } catch (e) {
      log("no ai_pay");
    }
    onChange(priceIndex);
    update();
  }

  void onChange(int index) async {
    priceIndex = index;
    double money = double.tryParse(price?[priceIndex]
                .price
                ?.split(RegExp(r"[\u4e00-\u9fa5]"))
                .join() ??
            "") ??
        0;
    coupons = await CouponApi.use1Coupons(
        gold: money, scene: PayScene.ai, otherId: '', roomId: roomId);
    var list = coupons?.where((element) => element.autoSelect == 1);
    if (list != null) {
      try {
        realPrice[index] = money - (list.first.gold ?? 0);
      } catch (e) {
        Logger().d(e);
      }
    }
    update();
  }
}
